package com.hlt.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hlt.entity.UserStats;
import com.hlt.mapper.UserStatsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class UserStatsUtils {

    @Autowired
    private UserStatsMapper userStatsMapper;

    /**
     * 更新用户统计信息
     * 
     * @param userId 用户ID
     * @param field  要更新的字段（likedCount、favoritesCount或followingCount）
     * @param isAdd  true表示增加，false表示减少
     */
    @Transactional
    public void updateStats(Integer userId, String field, boolean isAdd) {
        // 查询用户统计信息
        LambdaQueryWrapper<UserStats> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserStats::getUserId, userId);
        UserStats userStats = userStatsMapper.selectOne(queryWrapper);

        if (userStats == null) {
            // 如果不存在，创建新的统计记录
            userStats = new UserStats();
            userStats.setUserId(userId);
            userStats.setLikedPostsCount(0);
            userStats.setFavoritedPostsCount(0);
            userStats.setFollowersCount(0);
            userStats.setFollowingCount(0);
            userStatsMapper.insert(userStats);
        }

        // 根据字段更新相应的计数
        switch (field) {
            case "likedCount":
                userStats.setLikedPostsCount(userStats.getLikedPostsCount() + (isAdd ? 1 : -1));
                break;
            case "favoritedPostsCount":
                userStats.setFavoritedPostsCount(userStats.getFavoritedPostsCount() + (isAdd ? 1 : -1));
                break;
            case "followingCount":
                userStats.setFollowingCount(userStats.getFollowingCount() + (isAdd ? 1 : -1));
                break;
            case "followersCount":
                userStats.setFollowersCount(userStats.getFollowersCount() + (isAdd? 1 : -1));
                break;
        }
        userStatsMapper.updateById(userStats);
    }
}